package com.example.demo2.common.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo2.Demo2Application;
import com.example.demo2.entity.*;
import com.example.demo2.mapper.*;
import com.google.errorprone.annotations.Var;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class WebSecurityUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;


    @Autowired
    private SysRoleMapper sysRoleMapper;


    @Autowired
    private SysPermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //数据库查询用户是否存在
        SysUser sysUser;
        if(username.contains("@")){
            sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getEmail, username));
        }else {
            sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getPhone, username));
        }
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户不存在");
        }else {
            Long userId = sysUser.getId();
            List<SysRole> roleByUserId = sysRoleMapper.getRoleByUserId(userId);
            if(ObjectUtils.isNotEmpty(roleByUserId)){
                List<SysPermission> permissions = permissionMapper.getPermissionByRoleIds(roleByUserId.stream().map(SysRole::getId).collect(Collectors.toList()));
                return new SecurityUser(sysUser,permissions);
            }else {
                return new SecurityUser(sysUser);
            }
        }
    }
}
